<?php

namespace pmvc\mvc\wrapper;

use pmvc\ioc\ObjectFactory;
use pmvc\ioc\InitializingObject;
use pmvc\mvc\RequestWrapperMapping;
use pmvc\mvc\RequestWrapper;
use pmvc\mvc\Request;
use pmvc\util\StringUtil;
use pmvc\util\ClassUtil;
use Exception;

class RegexRequestWrapperMapping
	implements InitializingObject,
	RequestWrapperMapping {
		
	public $regexMap;

	private $objectFactory;

	public function initialize(ObjectFactory $objectFactory) {
		$this->objectFactory = $objectFactory;
	}

	public function getRequestWrappers(Request $request) {
		$url = $request->getRequestedUrl();
		$ret = Array();
		foreach ($this->regexMap as $key => $vals) {
			if (StringUtil::matches($key, $url, FALSE)) {
				if (!is_array($vals)) {
					$vals = Array($vals);
				}
				foreach ($vals as $val) {
					$obj = (is_string($val))
						? $this->objectFactory->getObjectById($val)
						: $val;
					if (!ClassUtil::isInstance($obj, 'pmvc\mvc\RequestWrapper')) {
						Log::error("Object with mapping {} is not a RequestWrapper", $key);
						throw new Exception("Object is not an instance of RequestWrapper");
					}
					array_push($ret, $obj);
				}
			}
		}
		return $ret;
	}
}

?>